import axios from 'axios'
import qs from 'qs'
import { URL, adminUrl } from './url'
import { isUrl } from '../assets/js/common'
import Vue from 'vue'

axios.defaults.withCredentials = true
// axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'

export default async function (url = '', data = {}, type = 'POST', urlAll = null, config = {} ) {

	url = url.indexOf('api') !== -1 ? adminUrl + url : URL + url ;

	if(urlAll === null && type == 'POST') data = qs.stringify(data);
	if( type == 'GET') data = {params: data}
	type = type.toUpperCase()

	var ajax = type == 'POST' ? axios.post(url, data,config) : axios.get(url, data,config);

    var promise = new Promise( ( resolve, rej) => {

        ajax = ajax.then(res => res.data)
            .then( res => {
				var isExecute = isUrl(res)
				if( !isExecute ) return;

                if(res.code == 1){
                    resolve(res)
                    return res
                }else{
					Vue.$vux.toast.show(res.msg)
				    // alert(res.msg)
                    throw new Error('状态码不是 1， 禁止代码执行了')
				}
            })
            .catch(e => {
                console.error(e)
            })

    }).catch( e => {
        console.log(e)
    })


	return promise
}
